package com.example.zzx.dovebook.welcome;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.FrameLayout;
import butterknife.BindView;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieCompositionFactory;
import com.example.baselibrary.commonutil.AppExecutors;
import com.example.baselibrary.widget.LottieFontViewGroup;
import com.example.zzx.dovebook.R;
import com.example.zzx.dovebook.base.BaseActivity;
import com.example.zzx.dovebook.main.MainActivity;
import com.example.zzx.dovebook.user.UserManager;

import java.io.FileOutputStream;
import java.io.InputStream;

public class WelcomeActivity extends BaseActivity {

    @BindView(R.id.welcome_font_group)
    LottieFontViewGroup fontViewGroup;

    private boolean isLoginPluginInstall;
    private boolean isAnimationFinish;

    private Handler mHandle = new Handler() {

        public void handleMessage(Message message) {
            if (isLoginPluginInstall && isAnimationFinish) {
                finish();
                startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
            }
        }
    };


    @Override
    protected void initViews(Bundle savedInstanceState) {
        createBookViews();
    }

    @Override
    protected void initOptions(Bundle savedInstanceState) {
        super.initOptions(savedInstanceState);

        UserManager.getInstance(this).updateBuffer();

        preloadLoginPlugin();

    }

    private void preloadLoginPlugin() {
        AppExecutors appExecutors = new AppExecutors();
        appExecutors.diskIO().execute(() -> {
            //预加载插件  加快插件的打开速度
            //由于项目升级到了AndroidX,RePlugin不支持AndroidX，所以舍弃插件化方案
//            if (RePlugin.getPluginInfo("login") != null) {
//                RePlugin.preload("login");
//            }
            isLoginPluginInstall = true;
            mHandle.sendEmptyMessage(1);
        });
    }

    private void createBookViews() {
        getMainHandler().post(() -> addBookView(getFileName('D')));
        getMainHandler().post(() -> addBookView(getFileName('O')));
        getMainHandler().post(() -> addBookView(getFileName('V')));
        getMainHandler().post(() -> addBookView(getFileName('E')));
        getMainHandler().post(() -> addBookView(getFileName('B')));
        getMainHandler().post(() -> addBookView(getFileName('O')));
        getMainHandler().post(() -> addBookView(getFileName('O')));
        getMainHandler().post(() -> addBookView(getFileName('K')));
        fontViewGroup.post(() -> fontViewGroup.play());
        fontViewGroup.setOnFinishListener(() -> {
            getMainHandler().postDelayed(() -> {
                isAnimationFinish = true;
                mHandle.sendEmptyMessage(1);
            }, 500L);
        });
    }

    private String getFileName(char key) {
        return key + ".json";
    }

    private void addBookView(String fileName) {
        LottieComposition result = LottieCompositionFactory.fromAssetSync(this, fileName).getValue();
        LottieAnimationView view = new LottieAnimationView(WelcomeActivity.this);
        view.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT));
        view.setComposition(result);
        fontViewGroup.addView(view);
    }



    /**
     * 从assets目录中复制某文件内容
     *  @param  assetFileName assets目录下的Apk源文件路径
     *  @param  newFileName 复制到/data/data/package_name/files/目录下文件名
     */
    private void copyAssetsFileToAppFiles(String assetFileName, String newFileName) {
        InputStream is = null;
        FileOutputStream fos = null;
        int buffsize = 1024;

        try {
            is = this.getAssets().open(assetFileName);
            fos = this.openFileOutput(newFileName, Context.MODE_PRIVATE);
            int byteCount = 0;
            byte[] buffer = new byte[buffsize];
            while((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected int getStatusBarColor() {
        return STATUS_BAR_LIGHT;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_welcome;
    }

    @Override
    protected Class createViewModel() {
        return null;
    }
}
